package com.yun.baymax.base;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.support.multidex.MultiDex;

import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.tinker.loader.app.DefaultApplicationLike;
import com.yun.baymax.BuildConfig;
import com.yun.baymax.bean.adapter.DaoMaster;
import com.yun.baymax.bean.adapter.DaoSession;
import com.yun.lib.utils.L;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobInstallation;

/**
 * Created by Administrator on 2017/4/10.
 */
public class ApplicationLike extends DefaultApplicationLike {
    private static final String BUGLYAPPID = "1400032033";
    private static final String BMOBAPPLICATIONID = "63396b859a02991d4b8b391264f572d3";
    private static ApplicationLike instance;
    public Context context;
    public DaoSession daoSession;
    public boolean isDebug = BuildConfig.DEBUG;

    public ApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    public static ApplicationLike getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        context = getApplication();
        if (!isDebug)
            Bugly.init(getApplication(), BUGLYAPPID, isDebug);
        L.isDebug = isDebug;
        initGreenDao();
        initBmob();
        IMHelper.getInstance().init(context);
        LocationHelper.getInstance().init();
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        MultiDex.install(base);
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

    private void initBmob() {
        Bmob.initialize(context, BMOBAPPLICATIONID);
        BmobInstallation.getCurrentInstallation().save();
    }

    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "notes-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }
}
